﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using XiaoMan.Service;
using XiaoMan.Model.Models;
using XiaoMan.API.Controllers;

namespace XiaoMan.API.Filter
{
    public class AuthFilterAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            bool flag = false;
            //要求请求中需要带有Authorization头
            if (actionContext.Request.Headers.Authorization != null)
            {
                var token = actionContext.Request.Headers.Authorization.Parameter ?? "";
                var userInfo = CacheManager.Get<Sys_Users>(token);
                if (userInfo != null)
                {
                    try
                    {
                        var AccessTimeSpan = actionContext.Request.Headers.GetValues("Access-TimeSpan").FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(AccessTimeSpan))
                        {
                            DateTime date = TimeHelp.ConvertStringToDateTime(AccessTimeSpan);
                            TimeSpan timespan = DateTime.Now - date;
                            flag = (int)timespan.TotalSeconds < 10;
                        }
                    }
                    catch (Exception)
                    {

                    }                
                }
            }
            if (!flag)
            {
                //如果验证不通过，则返回401错误，并且Body中写入错误原因
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("已拒绝访问,未登录或请求已过期"));
            }
        }
    }
}